<?php

namespace app\common\controller;

use PHPExcel_IOFactory;
use think\Controller;
use think\Db;
use think\Exception;
use think\Session;

class Index extends Controller
{
    public static function doExportExcel($data_list)
    {
        /*导入phpExcel核心类 */
        require_once VENDOR_PATH . 'PHPExcel/Classes/PHPExcel.php';
        require_once VENDOR_PATH . 'PHPExcel/Classes/PHPExcel/Writer/Excel5.php';     // 用于其他低版本xls
        require_once VENDOR_PATH . 'PHPExcel/Classes/PHPExcel/Writer/Excel2007.php'; // 用于 excel-2007 格式
        error_reporting(E_ALL);
        date_default_timezone_set('PRC');
        $objPHPExcel = new \PHPExcel();


        /*以下是一些设置 ，什么作者  标题啊之类的*/
        $objPHPExcel->getProperties()->setCreator("administrator")
            ->setLastModifiedBy("administrator")
            ->setTitle("数据EXCEL导出")
            ->setSubject("数据EXCEL导出")
            ->setDescription("excel")
            ->setKeywords("excel")
            ->setCategory("result file");
        $objPHPExcel->getDefaultStyle()->getFont()->setName('仿宋');
        $names = ['A', 'B', 'C', 'D'];
        foreach ($names as $value) {
            // 设置垂直居中
            $objPHPExcel->getActiveSheet()->getStyle($value)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        }
        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', "用户昵称")
            ->setCellValue('B1', "手机号")
            ->setCellValue('C1', "视频答题正确数")
            ->setCellValue('D1', "考试答题正确数");
//            ->setCellValue('E1',"性别")
//            ->setCellValue('F1',"专业")
//            ->setCellValue('G1',"做题个数")
//            ->setCellValue('H1',"成绩");
        //设置宽度
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(19);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(12);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(19);
//        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(9);
//        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(18);
//        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(10);
//        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(10);


        $num = 0;
        foreach ($data_list as $v) {
            if ($num < 2) {
                $num++;
            }
            $objPHPExcel->setActiveSheetIndex(0)
                //Excel的第A列，出数组的键值，下面以此类推
                ->setCellValue('A' . ($num += 1), $v['nick_name'])
                ->setCellValue('B' . ($num), $v['telphone'])
                ->setCellValue('C' . ($num), ' ' . $v['video_count'])
                ->setCellValue('D' . ($num), ' ' . $v['exam_count']);
//                ->setCellValue('E'.($num), $v['exam_count'])
//                ->setCellValue('F'.($num), $v['major'])
//                ->setCellValue('G'.($num), $v['doneCount'])
//                ->setCellValue('H'.($num), $v['grade']);
        }
        $objPHPExcel->getActiveSheet()->setTitle('User');
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . time() . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }

    public static function upload($user_id)
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('image');//500KB
        // 移动到框架应用根目录/public/uploads/ 目录下
        if ($file) {
            // 移动到服务器的上传目录 并且设置不覆盖
            $info = $file->validate(['size' => 1024000*5, 'ext' => 'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads', true, false);
            if ($info) {
                // 成功上传后 获取上传信息
                $file_path = $info->getSaveName();
                str_replace("\\", "/", $file_path);
                $data = [
                    'user_id' => $user_id,
                    'file_size' => $info->getSize(),
                    'create_time' => time(),
                    'filename' => $info->getInfo()['name'],
                    'file_path' => "/uploads/" . $info->getSaveName(),
                    'file_md5' => $info->hash('md5'),
                    'file_sha1' => $info->hash('sha1'),
                    'suffix' => $info->getExtension()
                ];
                Db::name('xwd_user_asset')->insert($data);
                return $data;
            } else {
                // 上传失败获取错误信息
                return GlobalVariable::promptErrorByJSON("错误", 500, "上传文件过大");
            }
        }
        return GlobalVariable::promptErrorByJSON("错误", 404, "无文件");
    }

    public static function uploadVideo()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('video');//500KB
        // 移动到框架应用根目录/public/uploads/ 目录下
        if ($file) {
            // 移动到服务器的上传目录 并且设置不覆盖
            $info = $file->validate(['size' => 1024*1024*500, 'ext' => 'mp4,avi'])->move(ROOT_PATH . 'public' . DS . 'videos', true, false);
            if ($info) {
                // 成功上传后 获取上传信息
                $file_path = $info->getSaveName();
                str_replace("\\", "/", $file_path);
                $data = [
                    'user_id' => Session::get('id', 'xgzx_user'),
                    'file_size' => $info->getSize(),
                    'create_time' => time(),
                    'filename' => $info->getInfo()['name'],
                    'file_path' => "/videos/" . $info->getSaveName(),
                    'file_md5' => $info->hash('md5'),
                    'file_sha1' => $info->hash('sha1'),
                    'suffix' => $info->getExtension()
                ];
                Db::name('Asset')->insert($data);
                return $data;
            } else {
                // 上传失败获取错误信息
                return $file->getError();
            }
        }
        return GlobalVariable::promptErrorByJSON("错误", 404, "无文件");
    }

    public static function doUploadExcel()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('excel');//500KB
        // 移动到框架应用根目录/public/uploads/ 目录下
        if ($file) {
            // 移动到服务器的上传目录 并且设置不覆盖
            $info = $file->validate(['size' => 1024 * 1024, 'ext' => 'xls'])->move(ROOT_PATH . 'public' . DS . 'excel', true, false);
            if ($info) {
                // 成功上传后 获取上传信息
                $file_path = $info->getSaveName();
                str_replace("\\", "/", $file_path);
                $data = [
                    'user_id' => Session::get('id', 'xgzx_user'),
                    'file_size' => $info->getSize(),
                    'create_time' => time(),
                    'filename' => $info->getInfo()['name'],
                    'file_path' => "/excel/" . $info->getSaveName(),
                    'file_md5' => $info->hash('md5'),
                    'file_sha1' => $info->hash('sha1'),
                    'suffix' => $info->getExtension()
                ];
                Db::name('Asset')->insert($data);
                return $data;
            } else {
                // 上传失败获取错误信息
                return $file->getError();
            }
        }
        return GlobalVariable::promptErrorByJSON("错误", 404, "无文件");
    }

    public static function doReadExcel($inputFileName)
    {
        /*导入phpExcel核心类 */
        require_once VENDOR_PATH . 'PHPExcel/Classes/PHPExcel.php';
        require_once VENDOR_PATH . 'PHPExcel/Classes/PHPExcel/Writer/Excel5.php';     // 用于其他低版本xls
        require_once VENDOR_PATH . 'PHPExcel/Classes/PHPExcel/Writer/Excel2007.php'; // 用于 excel-2007 格式
        error_reporting(E_ALL);
        date_default_timezone_set('PRC');
        date_default_timezone_set('PRC');
// 读取excel文件
        try {
            $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
            $objReader = PHPExcel_IOFactory::createReader($inputFileType);
            $objPHPExcel = $objReader->load($inputFileName);
        } catch (Exception $e) {
            return GlobalVariable::promptErrorByJSON("错误", 500, '加载文件发生错误："' . pathinfo($inputFileName, PATHINFO_BASENAME) . '": ' . $e->getMessage());
        }

        // 确定要读取的sheet，什么是sheet，看excel的右下角，真的不懂去百度吧
        $sheet = $objPHPExcel->getSheet(0);
        $highestRow = $sheet->getHighestRow();
        $highestColumn = $sheet->getHighestColumn();
        // 获取一行的数据
        $data = [];
        for ($row = 1; $row <= $highestRow; $row++) {
            // Read a row of data into an array
            $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
            //这里得到的rowData都是一行的数据，得到数据后自行处理，我们这里只打出来看看效果
            $data = $rowData;
        }
        return $data;
    }

    /**
     * 创建指定长度的随机字符串
     *
     * @param int $length
     * @return int|mixed
     */
    private function _generateInvitationCode($length = 6)
    {
        $chars = '123456789abcdefghijklmnpqrstuvwxyz';
        $string = "";
        for ($i = 0; $i < $length; $i++) {
            $string .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $string;
    }
}